package com.mediacloud.app.newsmodule.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.google.gson.Gson;
import com.mediacloud.app.assembly.views.XRefreashListView;
import com.mediacloud.app.model.activity.BaseBackActivity4NoDetail;
import com.mediacloud.app.model.news.ArticleItem;
import com.mediacloud.app.model.news.CatalogItem;
import com.mediacloud.app.model.news.kt.TypeX;
import com.mediacloud.app.model.utils.NeedTokenType;
import com.mediacloud.app.newsmodule.R;
import com.mediacloud.app.newsmodule.adaptor.hamap.HAMAPAdapter;
import com.mediacloud.app.newsmodule.adaptor.hamap.OnAttentionListener;
import com.mediacloud.app.newsmodule.guanzhu.GuanZhuModel;
import com.mediacloud.app.newsmodule.guanzhu.PageRecords;
import com.mediacloud.app.newsmodule.utils.NewsItemClickUtils;
import com.mediacloud.app.newsmodule.utils.ToastUtil;
import com.mediacloud.app.newsmodule.utils.spider.FollowKit;
import com.mediacloud.app.newsmodule.utils.spider.IAccessToken;
import com.mediacloud.app.newsmodule.utils.spider.IAttentionCall;
import com.mediacloud.app.newsmodule.utils.spider.SpiderKit;
import com.mediacloud.app.reslib.util.DataInvokeUtil;
import com.mediacloud.app.reslib.util.ModuleReferenceConfig;
import com.mediacloud.app.user.model.UserInfo;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/**
 * Created by x on 2018/3/23.
 */

public class HAMAPActivity extends BaseBackActivity4NoDetail implements XRefreashListView.IXListViewListener, OnAttentionListener, Callback {
    private XRefreashListView mListView = null;
    private HAMAPAdapter adapter = null;
    private int pageNum = 1;
    private List<PageRecords> itemList;
    private boolean isRefresh = true;
    private UserInfo userInfo = null;

    @Override
    public int getLayoutResID() {
        return R.layout.activityhamap;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initViews();
        getAccessToken();
        setTitle(getIntent().getStringExtra("title"));
    }

    private void initViews() {
        mListView = mRootView.findViewById(R.id.listView);
        mListView.setPullLoadEnable(false);
        mListView.setPullRefreshEnable(false);
        mListView.setXListViewListener(this);
        itemList = new ArrayList<>();
        adapter = new HAMAPAdapter(this, itemList);
        adapter.setOnAttentionListener(this);
        mListView.setAdapter(adapter);

    }

    /**
     * 获取关注列表的接口
     */
    private void getListData() {
        DataInvokeUtil.guanzhuliebiao(pageNum, 15, userInfo != null ? userInfo.getAccess_token() : null, null,null,this);
    }

    /**
     * 获取自媒体的token , 判断是否登录了的
     */
    private void getAccessToken() {
        userInfo = UserInfo.getUserInfo(this);
        if (userInfo.isLogin()) {
            SpiderKit.INSTANCE.getAccessToken(this, userInfo, new IAccessToken() {
                @Override
                public void success(@NonNull UserInfo userInfo) {
                    onRefresh();
                }

                @Override
                public void fail() {
                    getListData();
                }
            });
        } else {
            getListData();
        }
    }


    /**
     * 来自Adapter item 点击关注的回掉
     *
     * @param record
     */
    @Override
    public void Attention(PageRecords record) {
        if (userInfo == null) { // 没登录
//            ToastUtil.show(this, R.string.please_login);
            Intent intent = new Intent();
            intent.setClassName(this, ModuleReferenceConfig.LoginActivity);
            startActivityForResult(intent, 123);
        } else {

            FollowKit.INSTANCE.followOrNot(null,this, record.getSpiderId(),record.getUserNickName(), new IAttentionCall() {
                @Override
                public void onAttentionResult(boolean attention) {

                    adapter.notifyDataSetChanged();
                }

                @Override
                public void onAttentionFail() {

                }
            },null);

        }
    }

    /**
     * 来自Adapter item 点击头像的回掉
     *
     * @param url 去Author的主页
     */
    @Override
    public void AuthorHome(String url) {
        if (!TextUtils.isEmpty(url)) {
            ArticleItem item = new ArticleItem();
            item.setTitle("");
            item.setType(TypeX.NEWS.LINK);
            item.setLinkNews(false);
            item.setUrl(url);
            boolean collection = false;
            boolean share = true;
            NewsItemClickUtils.OpenItemNewsHandle(this, TypeX.NEWS.LINK, item, new CatalogItem(), NeedTokenType.Delayed, collection, share);

        }
    }

    /**
     * ListView刷新
     */
    @Override
    public void onRefresh() {
        mListView.setPullLoadEnable(false);
        mListView.setPullRefreshEnable(false);
        isRefresh = true;
        pageNum = 1;
        getListData();
    }

    /**
     * ListView加载更多
     */
    @Override
    public void onLoadMore() {
        mListView.setPullLoadEnable(false);
        mListView.setPullRefreshEnable(false);
        isRefresh = false;
        pageNum++;
        getListData();
    }

    public void onFinished() {
        mListView.stopLoadMore();
        mListView.stopRefresh();
        mListView.setPullRefreshEnable(true);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        getAccessToken();
    }

    @Override
    public void onFailure(Call call, IOException e) {
        onFinished();
    }

    @Override
    public void onResponse(Call call, Response response) throws IOException {
        onFinished();
        Gson gson = new Gson();
        GuanZhuModel result = gson.fromJson(response.body().string(), GuanZhuModel.class);
        if (result.getSuccess()) {
            //是否还有下一页
            if (result.getData().getHasNextPage()) {
                mListView.setPullLoadEnable(true);
            } else {
                mListView.setPullLoadEnable(false);
            }
            if (result.getData().getPageRecords() != null) {
                if (isRefresh) itemList.clear();
                itemList.addAll(result.getData().getPageRecords());
                adapter.notifyDataSetChanged();
            }
        }
    }
}